package com.example.daxiguaforharmony.slice;

import com.example.daxiguaforharmony.MainAbility;
import com.example.daxiguaforharmony.ResourceTable;
import com.example.daxiguaforharmony.SharedService;
import com.example.daxiguaforharmony.game.core.renderers.Sprite;
import com.example.daxiguaforharmony.manager.INewsDemoIDL;
import com.example.daxiguaforharmony.manager.NewsDemoIDLStub;
import com.example.daxiguaforharmony.manager.ShareFaManager;
import com.example.daxiguaforharmony.provider.DevicesListProvider;
import com.example.daxiguaforharmony.ui.DeviceSelectDialog;
import com.example.daxiguaforharmony.utils.DialogUtils;
import com.example.daxiguaforharmony.utils.ImageUtil;
import com.example.daxiguaforharmony.utils.LogUtil;
import com.example.daxiguaforharmony.utils.LogUtils;
import com.example.daxiguaforharmony.widget.widget.WidgetImpl;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.render.Paint;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.AbilityInfo;
import ohos.bundle.ElementName;
import ohos.bundle.IBundleManager;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.interwork.utils.PacMapEx;
import ohos.media.image.PixelMap;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteException;

import java.util.ArrayList;
import java.util.List;

//import ohos.agp.components.webengine.WebView;

/**
 * Full screen ability slice
 */
public class ResultsAbilitySlice extends AbilitySlice {
    public static final String INTENT_TITLE = "intent_title";
    public static final String INTENT_READ = "intent_read";
    public static final String INTENT_LIKE = "intent_like";
    public static final String INTENT_CONTENT = "intent_content";
    //public static final String INTENT_IMAGE = "intent_image";
    static final HiLogLabel label=new HiLogLabel(HiLog.LOG_APP,0x0001,"获取跳转结果测试");
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, WidgetImpl.class.getName());
    private static final String TAG2 = "ResultsAbilitySlice";
    //Image image;
    Image imageBj;
    Image imageBj2;
    PixelMap imagePixelMap;
    PixelMap imagePixelMap2;

    private String reads;
    private String likes;
    private String title;
    private String content;
    //private String image;
    private static final int WAIT_TIME = 30000;
    private static final int DIALOG_SIZE_WIDTH = 900;
    private static final int DIALOG_SIZE_HEIGHT = 800;
    private DependentLayout parentLayout;
    private TextField commentFocus;
    private Button iconShared;
    private Image imgFind;
    private CommonDialog dialog;
    private List<DeviceInfo> devices = new ArrayList<>();

    private static final String PERMISSION_DATASYNC = "ohos.permission.DISTRIBUTED_DATASYNC";
    private static final int MY_PERMISSION_REQUEST_CODE = 1;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        // hide status bar
        this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);
        this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);

        // adapt orientation
        int orientation = getResourceManager().getConfiguration().direction;
        super.setUIContent(ResourceTable.Layout_results);

        reads = intent.getStringParam(INTENT_READ);//当前
        likes = intent.getStringParam(INTENT_LIKE);//最高
        title = intent.getStringParam(INTENT_TITLE);
        content = intent.getStringParam(INTENT_CONTENT);//tip
        //image = intent.getStringParam(INTENT_IMAGE);

        System.out.println("findComponentById is start=================");
        if (findComponentById(ResourceTable.Id_numcur) instanceof Image) {
            imageBj = (Image) findComponentById(ResourceTable.Id_numcur);
        }
        if (findComponentById(ResourceTable.Id_numbest) instanceof Image) {
            imageBj2 = (Image) findComponentById(ResourceTable.Id_numbest);
        }
        System.out.println("reads="+reads+"======likes="+likes+"====title="+title+"===content="+content);
        //int score = (int)intent.getIntParam("score", 0);
        reads = reads == null || reads == "" ? "0":reads;
        likes = likes == null || likes == "" ? "0":likes;
        //Integer score = Integer.parseInt(reads);
//        System.out.println("getIntParam得分======"+score);
//



        System.out.println("getPixelMapFromResource is start=================");
        imgFind = new Image(getContext());
        //imagePixelMap = this.getPixelMapFromResource(ResourceTable.Id_logo);
        Image image = new Image(this);
        image.setPixelMap(ResourceTable.Media_num1);
        imagePixelMap = image.getPixelMap();

        if(imagePixelMap != null) {
            System.out.println("imagePixelMap is start=================");
            Paint paint = new Paint();
            ImageUtil.mirrorImage(imageBj,imagePixelMap,reads,paint,66,60,22);
            System.out.println("imagePixelMap is ok===============");
        }

        Image image2 = new Image(this);
        image2.setPixelMap(ResourceTable.Media_num2);
        imagePixelMap2 = image2.getPixelMap();
        if(imagePixelMap2 != null) {
            System.out.println("imagePixelMap2 is start=================");
            Paint paint = new Paint();
            ImageUtil.mirrorImage(imageBj2,imagePixelMap2,likes,paint,69,60,30);
            System.out.println("imagePixelMap2 is ok===============");
        }


        Button btnOk = (Button) findComponentById(ResourceTable.Id_btn_goon);
        btnOk.setClickedListener(l -> {
            Intent intent2 = new Intent();
            Operation operation =
                    new Intent.OperationBuilder()
                            .withBundleName(getBundleName())
                            .withAbilityName(MainAbility.class.getName())
                            .withAction("action.game")
                            .build();
            intent2.setOperation(operation);
            intent2.setParam(GameAbilitySlice.INTENT_IS_SHOW_START, "1");
            intent2.setParam(GameAbilitySlice.INTENT_MY_SCORE, "0");
            intent2.setParam(GameAbilitySlice.INTENT_MY_FRUITS, "");
            startAbility(intent2);

            //present(new GameAbilitySlice(), new Intent());// Ability 跳转
            terminate();//销毁窗体
            //present(new GameAbilitySlice(), new Intent());// 跳转
        });


        Text txt = (Text) findComponentById(ResourceTable.Id_txt);
        //String tip = ImageUtil.getGameTip(score,this);
        txt.setText(content);


        initView();
        initListener();

    }

    private void initView() {
        //parentLayout = (DependentLayout) findComponentById(ResourceTable.Id_parent_layout);
        //commentFocus = (TextField) findComponentById(ResourceTable.Id_text_file);
        iconShared = (Button) findComponentById(ResourceTable.Id_btn_Shared);
        //Text newsRead = (Text) findComponentById(ResourceTable.Id_read_num);
        //Text newsLike = (Text) findComponentById(ResourceTable.Id_like_num);
        //Text newsTitle = (Text) findComponentById(ResourceTable.Id_title_text);
        //Text newsContent = (Text) findComponentById(ResourceTable.Id_title_content);
        imgFind = (Image) findComponentById(ResourceTable.Id_qianyi);
        //newsRead.setText("reads: " + reads);
        //newsLike.setText("likes: " + likes);
        //newsTitle.setText("Original title: " + title);
        //newsContent.setText(content);
        //newsImage.setPixelMap(CommonUtils.getPixelMapFromPath(this, image));
    }

    private void initListener() {
//        parentLayout.setTouchEventListener(
//                (component, touchEvent) -> {
//                    if (commentFocus.hasFocus()) {
//                        commentFocus.clearFocus();
//                    }
//                    return true;
//                });

        iconShared.setClickedListener(
                v -> {
//                    initDevices();
//                    showDeviceList();
//                    sharedclick();
                    findClick();
                });
        imgFind.setClickedListener(
                v -> {
                    findClick();
                });
    }

    private void sharedclick()
    {
        System.out.println("进入sharedclick===");
        PacMapEx pacMap = new PacMapEx();
        pacMap.putObjectValue(ShareFaManager.SHARING_FA_TYPE, 0);
        pacMap.putObjectValue(ShareFaManager.HM_BUNDLE_NAME, getBundleName());
        pacMap.putObjectValue(ShareFaManager.SHARING_EXTRA_INFO, "xxxxxxxx");
        pacMap.putObjectValue(ShareFaManager.HM_ABILITY_NAME, MainAbility.class.getName());
        pacMap.putObjectValue(ShareFaManager.SHARING_CONTENT_INFO, "xxxxxxx");
        //pacMap.putObjectValue(ShareFaManager.SHARING_THUMB_DATA, picByte);
        //pacMap.putObjectValue(ShareFaManager.HM_FA_ICON, iconByte);
        pacMap.putObjectValue(ShareFaManager.HM_FA_NAME, "FAShareDemo");
        // 第一个参数为appid，在华为AGC创建原子化服务时自动生成。
        ShareFaManager.getInstance(this).shareFaInfo("581228865511237888", pacMap);
    }

    private void initDevices() {
        if (verifySelfPermission(PERMISSION_DATASYNC) != IBundleManager.PERMISSION_GRANTED) {
            if (canRequestPermission(PERMISSION_DATASYNC)) {
                requestPermissionsFromUser(new String[] {PERMISSION_DATASYNC}, MY_PERMISSION_REQUEST_CODE);
            }
        }

        System.out.println("进入initDevices===");
        if (devices.size() > 0) {
            devices.clear();
        }
        List<DeviceInfo> deviceInfos = DeviceManager.getDeviceList(DeviceInfo.FLAG_GET_ONLINE_DEVICE);
        devices.addAll(deviceInfos);
    }

    private void showDeviceList() {
        System.out.println("进入showDeviceList===");
        dialog = new CommonDialog(ResultsAbilitySlice.this);
        dialog.setAutoClosable(true);
        dialog.setTitleText(" 分享到其它设备");
        dialog.setSize(DIALOG_SIZE_WIDTH, DIALOG_SIZE_HEIGHT);
        ListContainer devicesListContainer = new ListContainer(getContext());
        DevicesListProvider devicesListProvider = new DevicesListProvider(devices, this);
        devicesListContainer.setItemProvider(devicesListProvider);
        devicesListContainer.setItemClickedListener(
                (listContainer, component, position, id) -> {
                    dialog.destroy();
                    startAbilityFA(devices.get(position).getDeviceId());
                });
        devicesListProvider.notifyDataChanged();
        dialog.setContentCustomComponent(devicesListContainer);
        dialog.show();
    }

    private void startAbilityFA(String devicesId) {
        System.out.println("startAbilityFA==="+devicesId);
        Intent intent = new Intent();
        Operation operation =
                new Intent.OperationBuilder()
                        .withDeviceId(devicesId)
                        .withBundleName(getBundleName())
                        .withAbilityName(SharedService.class.getName())
                        .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                        .build();
        intent.setOperation(operation);
        boolean connectFlag =
                connectAbility(
                        intent,
                        new IAbilityConnection() {
                            @Override
                            public void onAbilityConnectDone(ElementName elementName, IRemoteObject remoteObject, int i) {
                                INewsDemoIDL sharedManager = NewsDemoIDLStub.asInterface(remoteObject);
                                try {
                                    System.out.println("startAbilityFA==="+title+reads);
                                    sharedManager.tranShare(title, reads, likes, content);
                                } catch (RemoteException e) {
                                    LogUtils.i(TAG2, "connect successful,but have remote exception===");
                                }
                            }

                            @Override
                            public void onAbilityDisconnectDone(ElementName elementName, int i) {
                                System.out.println("onAbilityDisconnectDone==="+title+reads);
                                disconnectAbility(this);
                            }
                        });
        DialogUtils.toast(
                this, connectFlag ? "分享成功" : "Sharing failed. Please try again later.", WAIT_TIME);
    }


    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);
    }

    @Override
    public void onActive() {
        Intent intent = getAbility().getIntent();
        int score = intent.getIntParam("score",0);
        System.out.println("获取结果3=====:"+score);
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        HiLog.info(label,"请求code2=====:"+requestCode);
        HiLog.info(label,"响应code2====:"+resultCode);
        System.out.println("请求code2=====:"+requestCode);
        System.out.println("响应code2=====:"+resultCode);
        if(requestCode==100)
        {
            HiLog.info(label,"请求code匹配2====");
            if(resultData!=null)
            {
                HiLog.info(label,"请求结果2=====:"+resultData.getStringParam("transVal"));
            }
        }
        super.onAbilityResult(requestCode, resultCode, resultData);
    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        HiLog.info(label,"请求code=====:"+requestCode);
        System.out.println("请求code=====:"+requestCode);
        if (requestCode == 100) {
            // Process resultIntent here.
            HiLog.info(label,"请求code匹配=====");
            System.out.println("请求code匹配=====:"+requestCode);
            if(resultIntent.getParam("transVal")!=null)
            {
                HiLog.info(label,"请求结果=====:"+resultIntent.getStringParam("transVal"));
                System.out.println("请求结果=====:"+resultIntent.getStringParam("transVal"));
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public void findClick()
    {
        System.out.println("findClick===");
        DeviceSelectDialog dialog = new DeviceSelectDialog(this.getContext());
        dialog.setListener(deviceInfo -> {
            LogUtil.info(TAG2, "continue button click===");
            LogUtil.debug(TAG2, ": device name === " + deviceInfo.getDeviceName().toString());
            System.out.println(TAG2 + ": device name === " + deviceInfo.getDeviceName().toString());

            try {
                // 开始任务迁移
                //imgFind.setImageAndDecodeBounds(ResourceTable.Media_qianyi0);
                //sharedManager.tranShare(title, reads, likes, content);
                //continueAbility();
                //this.continueAbility(deviceInfo.getDeviceId());
                // 远程启动FA
                Intent remoteIntent = new Intent();
// 指定待启动FA的bundleName和abilityName
// 例如：BUNDLE_NAME = "com.huawei.codelab"
//     ABILITY_NAME = "com.huawei.codelab.MainAbility"
// 设置分布式标记，表明当前涉及分布式能力
                Operation operation = new Intent.OperationBuilder().withDeviceId(deviceInfo.getDeviceId())
                        .withBundleName(getBundleName())
                        .withAbilityName(MainAbility.class.getName())
                        .withAction("action.results")
                        .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                        .build();
                remoteIntent.setOperation(operation);
                remoteIntent.setParam(ResultsAbilitySlice.INTENT_TITLE, title);
                remoteIntent.setParam(ResultsAbilitySlice.INTENT_READ, reads);
                remoteIntent.setParam(ResultsAbilitySlice.INTENT_LIKE, likes);
                remoteIntent.setParam(ResultsAbilitySlice.INTENT_CONTENT, content);
                try {
                    // 目标设备是否包含指定FA
                    List<AbilityInfo> abilityInfoList = getBundleManager().queryAbilityByIntent(remoteIntent, 0, 0);
                    if (abilityInfoList != null && !abilityInfoList.isEmpty()) {
                        startAbility(remoteIntent);
                    }
                } catch (RemoteException e) {
                    // 处理异常
                    System.out.println("findclick error"+e.getMessage());
                }
                LogUtil.info(TAG2, "continue button click end===");
            } catch (IllegalStateException | UnsupportedOperationException e) {
                //WidgetHelper.showTips(this, ResourceTable.String_tips_mail_continue_failed);
                LogUtil.info(TAG2, "continue button click error==="+e.getMessage());
            }
            dialog.hide();
            imgFind.setImageAndDecodeBounds(ResourceTable.Media_qianyi0);
        });
        dialog.show();
        //imgFind.setVisibility(Component.HIDE);
        //imgFind.setImageAndDecodeBounds(ResourceTable.Media_qianyi0);
        //imgFind.setVisibility(Component.VISIBLE);


    }


}
